package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CookieUtil;
import com.nowcoder.community.util.HostHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.naming.Name;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @BelongsProject: community
 * @BelongsPackage: com.nowcoder.community.controller.interceptor
 * @Author: Master_XXJS
 * @CreateTime: 2022-09-26  15:54
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;

    /**
     * 在request请求之前，判断一下是否是登录状态（拥有用户的信息）
     * 将用户的信息存入到 本地线程中，方便传回去到model页面中
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");

        if (ticket != null){
            //查询登录的凭证
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            //检查登录凭证是否过期，或者有值
            //登录的凭证不等于 null，status 为0账号有效，过期时间在当前时间 new date（）之后
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())){
                //根据凭证查询用户
                User user = userService.findUserById(loginTicket.getUserId());
                //在本次的请求中进行持有该用户的信息
                hostHolder.setUser(user);

                //Security底层代码的逻辑
                //因为我们没有使用 security 的登录认证，所以我们的 手动 给SecurityContextHolder 进行赋值
                //构建用户认证的结果，并且存入 SecurityContext。以便于 Security 进行授权
                Authentication authenticationToken = new UsernamePasswordAuthenticationToken(
                        user, user.getPassword(), userService.getAuthorities(user.getId()));
                //将 认证对象 传入到 SecurityContextHolder 中
                SecurityContextHolder.setContext(new SecurityContextImpl(authenticationToken));
            }
        }
        return true;
    }

    /**
     * controller 请求完成之后，将用户的信息返回到页面
     * 渲染视图之前回调
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null){
            modelAndView.addObject("loginUser",user);
        }
    }

    /**
     * 整个request请求处理完毕回调方法，即在视图渲染完毕时回调
     * 将threadLocal本地线程的资源释放，不然容易导致内存泄漏
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求完成之后，hostHolder需要进行清除，不然浪费资源
        hostHolder.clear();
        //SpringSecurityContext在本次的请求完成之后，信息需要进行删除
        SecurityContextHolder.clearContext();
    }
}

